package cn.edu.sgu.www.mhxysy.service.system.impl;

import cn.edu.sgu.www.mhxysy.consts.RedisKeyPrefixes;
import cn.edu.sgu.www.mhxysy.dto.system.MenuTreeDTO;
import cn.edu.sgu.www.mhxysy.dto.system.UserMenuDTO;
import cn.edu.sgu.www.mhxysy.feign.clients.pms.PmsFeignService;
import cn.edu.sgu.www.mhxysy.redis.RedisUtils;
import cn.edu.sgu.www.mhxysy.service.system.UserMenuService;
import cn.edu.sgu.www.mhxysy.util.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author 沐雨橙风ιε
 * @version 1.0
 */
@Service
public class UserMenuServiceImpl implements UserMenuService {

    private final RedisUtils redisUtils;
    private final PmsFeignService feignService;

    @Autowired
    public UserMenuServiceImpl(RedisUtils redisUtils, PmsFeignService feignService) {
        this.redisUtils = redisUtils;
        this.feignService = feignService;
    }

    @Override
    public void control(MenuTreeDTO menuTreeDTO) {
        String userId = UserUtils.getUserId();

        List<String> displayIds = menuTreeDTO.getDisplayIds();
        List<String> hideIds = menuTreeDTO.getHideIds();

        // 创建应该临时的list，用来保存displayIds
        List<String> temp = new ArrayList<>(displayIds);

        // 两个list都不为空，去除两个list共有的元素
        if (!displayIds.isEmpty() && !hideIds.isEmpty()) {
            // 删除temp和hideIds共有的元素
            temp.removeIf(new Predicate<String>() {
                @Override
                public boolean test(String str) {
                    return hideIds.contains(str);
                }
            });

            // 删除hideIds和displayIds共有的元素
            hideIds.removeIf(new Predicate<String>() {
                @Override
                public boolean test(String str) {
                    return displayIds.contains(str);
                }
            });
        }

        menuTreeDTO.setUserId(userId);
        menuTreeDTO.setDisplayIds(temp);
        menuTreeDTO.setHideIds(hideIds);

        feignService.control(menuTreeDTO);

        // 删除缓存
        deleteCache(userId);
    }

    @Override
    public void updateSort(UserMenuDTO userMenuDTO) {
        String userId = UserUtils.getUserId();

        userMenuDTO.setUserId(userId);

        feignService.updateSort(userMenuDTO);

        // 删除缓存
        deleteCache(userId);
    }

    /**
     * 删除缓存
     */
    private void deleteCache(String userId) {
        redisUtils.delete(RedisKeyPrefixes.PREFIX_USER_LEFT_MENUS + userId);
        redisUtils.delete(RedisKeyPrefixes.PREFIX_USER_MENU_TREE + userId);
    }

}